package com.wgchao.authmanager.infrastructure.repository;

import com.wgchao.authmanager.domain.model.Administrator;
import com.wgchao.authmanager.domain.repository.AdministratorRepository;
import com.wgchao.authmanager.infrastructure.convert.em.UserInfoConvert;
import com.wgchao.authmanager.infrastructure.exception.IdNotExistException;
import com.wgchao.authmanager.infrastructure.exception.IdentifyUsedException;
import com.wgchao.authmanager.infrastructure.jpa.entity.AgencyInfo;
import com.wgchao.authmanager.infrastructure.jpa.entity.UserInfo;
import com.wgchao.authmanager.infrastructure.jpa.repository.AgencyInfoJpaRepository;
import com.wgchao.authmanager.infrastructure.jpa.repository.UserInfoJpaReposotory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
import java.util.Date;

/**
 * @作者：wgchao
 * @时间：21:58 2020/5/5 0005
 * @用途：
 **/
@Component
public class AdministratorRepositoryImpl implements AdministratorRepository {
    @Autowired
    private UserInfoJpaReposotory userInfoJpaReposotory;
    @Autowired
    private UserInfoConvert userInfoConvert;
    @Autowired
    private AgencyInfoJpaRepository agencyInfoJpaRepository;

    @Override
    public String encryptePwd(String password) {
        return new BCryptPasswordEncoder().encode(password);
    }

    @Override
    public void add(Administrator administrator) {
        if(administrator.findId() == null  || administrator.findId().compareTo(0L) <= 0){
            UserInfo userInfo = userInfoJpaReposotory.findFirstByUname(administrator.getUname());
            if(userInfo != null){
                throw new IdentifyUsedException("账户名已被占用");
            }
        }
        UserInfo userInfo = userInfoConvert.toEntity(administrator);
        userInfo.setDel(false);
        userInfo = userInfoJpaReposotory.save(userInfo);
    }

    @Override
    public void remove(Administrator administrator, String operator) {
        UserInfo userInfo = userInfoConvert.toEntity(administrator);
        if(userInfo.getId() == null){
            throw new IdNotExistException("主键缺失");
        }
        userInfo.setDel(true);
        userInfo.setLastUpdateUser(operator);
        userInfo.setLastUpdateTime(new Date());
        userInfo = userInfoJpaReposotory.save(userInfo);
    }

    @Override
    public Administrator get(String id) {
        UserInfo userInfo = userInfoJpaReposotory.findFirstByUnameAndDelFalse(id);
        if(userInfo == null){
            return null;
        }
        AgencyInfo agencyInfo = agencyInfoJpaRepository.findFirstByAgencyCodeAndDelFalse(userInfo.getAgencyCode());
        if(agencyInfo == null || agencyInfo.isDisabled()){
            return null;
        }
        return userInfoConvert.toModel(userInfo);
    }
}
